package alt.fr.ma.np.activities;

import java.util.ArrayList;

import alt.fr.ma.np.R;
import alt.fr.ma.np.soap.Parameter;
import alt.fr.ma.np.soap.SOAPRequest;
import alt.fr.ma.np.tools.GenericTextWatcher;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Display;
import android.view.Surface;
import android.view.View;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;

public class LoginActivity extends Activity {

	private ProgressDialog progressDialog;
	private SOAPRequest soapRequest;
	private String login;
	private String password;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.d("NORMAL - LoginActivity", "Starting LoginActivity!");

		Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE))
				.getDefaultDisplay();
		switch (display.getRotation()) {
		case Surface.ROTATION_0:
			setContentView(R.layout.login);
			break;
		case Surface.ROTATION_90:
			setContentView(R.layout.login_landscape);
			break;
		case Surface.ROTATION_180:
			break;
		case Surface.ROTATION_270:
			break;
		}
		
		((TextView) findViewById(R.id.loginField)).addTextChangedListener(new GenericTextWatcher(findViewById(R.id.loginError)));
		((TextView) findViewById(R.id.passwordField)).addTextChangedListener(new GenericTextWatcher(findViewById(R.id.passwordError)));
	}

	@Override
	public void onBackPressed() {
		finish();
	}

	public void loginAction(View view) {
		switch (view.getId()) {
		case R.id.signInButton:

			new AsyncTask<Integer, Integer, Boolean>() {

				@Override
				protected void onPreExecute() {

					login = ((TextView) findViewById(R.id.loginField))
							.getText().toString();
					password = ((TextView) findViewById(R.id.passwordField))
							.getText().toString();

					boolean cancel = false;

					if (login.equals("")) {
						((ImageView) findViewById(R.id.loginError))
								.setVisibility(View.VISIBLE);
						cancel = true;
					}
					
					if (password.equals("")) {
						((ImageView) findViewById(R.id.passwordError))
								.setVisibility(View.VISIBLE);
						cancel = true;
					}
					
					if (!cancel) {
						ArrayList<Parameter> params = new ArrayList<Parameter>();

						String loginInformation = "";

						loginInformation += login + "|";
						loginInformation += password + "|";

						params.add(new Parameter("sAction", "Login"));
						params.add(new Parameter("sParams", loginInformation));

						soapRequest = new SOAPRequest("sociablon",
								"WSTechnicalUser", "Sociablon01",
								"WSSociablonWebService", params);

						progressDialog = ProgressDialog.show(
								LoginActivity.this, "", "Signing in...");
					} else
						this.cancel(false);
				}

				@Override
				protected Boolean doInBackground(Integer... params) {

					// Starting the SOAP request and waiting for the response
					Thread request = new Thread(soapRequest);
					try {
						request.start();
						request.join();
						progressDialog.dismiss();
					} catch (InterruptedException e) {
						Log.d("ERROR - LoginActivity", "InterruptedException",
								e);
					}

					String soapResponse = null;
					try {
						soapResponse = soapRequest.getSOAPResponse();
					} catch (Exception e) {
						Log.d("ERROR - LoginActivity",
								"SOAPResponseException: " + e.getMessage());
					}

					Log.d("NORMAL - LoginActivity", "SOAPResponse = "
							+ soapResponse);

					return (soapResponse != null)
							&& soapResponse.charAt(0) == ('1') ? true : false;
				}

				@Override
				protected void onPostExecute(Boolean result) {
					if (result) {

						// The user is sucessfully authenticetd, we store its
						// credentials in the preferences if he checked
						// 'remember
						// me'
						if (((CheckBox) findViewById(R.id.rememberMe))
								.isChecked()) {
							Editor e = PreferenceManager
									.getDefaultSharedPreferences(
											LoginActivity.this).edit();
							e.putString("login", login);
							e.putString("password", password);
							e.commit();
						}

						startActivity(new Intent(LoginActivity.this,
								MainActivity.class));

					} else {
						//show error
					}
				}
			}.execute();
			break;
		}
	}

	public void registerAction(View view) {
		switch (view.getId()) {
		case R.id.registerButton:
			startActivity(new Intent(this, RegisterActivity.class));
			break;
		}
	}
}
